const express = require('express');
const shop = express.Router();
const {Shop} = require('../db/mongoose');

function sortData(a,b){
    if(b.rating == a.rating){
        if(a.delivery_duration == b.delivery_duration){
            if(b.sales_monthly == a.sales_monthly) return a.distance - b.distance
            else return b.sales_monthly - a.sales_monthly
        }
        else return a.delivery_duration - b.delivery_duration
    }
    else return b.rating - a.rating;
}

// 获取所有商品
shop.get('/getAllShops',(req,res)=>{
    Shop.find((err,data)=>{
        if(err) return res.status(200).json({
            code:'1001',
            message:'系统错误'
        })
        if(data.length == 0) return res.status(200).json({
            code:'2001',
            message:'未找到数据'
        })
        data.sort(sortData);
        return res.status(200).json({
            code:'2000',
            message:'成功找到数据',
            data
        })
    })
})

// 筛选 活动优惠店铺
shop.post('/filterDiscountShops',(req,res)=>{
    let activities = req.body.discount.filter(item=>{
        return item.type == 'activities';
    });
    let welfares = req.body.discount.filter(item=>{
        return item.type == 'welfares';
    })
    let delivery_fee = req.body.discount.filter(item=>{
        return item.type == 'delivery_fee';
    })
    console.log('activities',activities);
    console.log('welfares',welfares);
    console.log('delivery_fee',delivery_fee);
})

// 筛选器 筛选店铺
shop.post('/filterShops',(req,res)=>{
    let duration = req.body.duration;
    let distance = req.body.distance;
    let discount = req.body.discount;
    let service = req.body.service;
    console.log(duration,distance,discount,service);
    Shop.find({
        delivery_duration:{$lte:duration},
        distance:{$lte:distance}
    },(err,data)=>{
        if(err) return res.status(200).json({
            code:'1001',
            message:'系统错误'
        })
        if(data.length == 0) return res.status(200).json({
            code:'2001',
            message:'未找到数据'
        })
        console.log('data',data);
        let discountFilterData = [];
        for(let i = 0; i<discount.length; i++) {
            let filter = data.filter(item=>{
                for(let j = 0; j<item.discount.activities.length; j++){
                    if(item.discount.activities[j].name == discount[i]) return;
                }
                for(let j = 0; j<item.discount.welfares.length; j++){
                    if(item.discount.welfares[j].name == discount[i]) return;
                }
                // item.discount.activities
            })
        }
    })
})

module.exports = shop;